//
//  MQComposeViewController.swift
//  SinaWeiBo
//
//  Created by 毛强 on 16/1/28.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class MQComposeViewController: UIViewController ,UITextViewDelegate{
    
    var composeToolBarAnimation:Bool = true
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    //监听事件
    @objc private func didClickEmoticonBtn(noti:NSNotification){
//        printfLog(noti.userInfo!["emoticon"] as! MQEmoticon)
        let emoticon = noti.userInfo!["emoticon"]as! MQEmoticon
    
        
        if emoticon.type == "0"{
            //图片表情
            let imageName = "\(emoticon.path!)/\(emoticon.png!)"
            let image = UIImage(named: imageName, inBundle: MQEmoticonTools.shareTools.emoticonBundle, compatibleWithTraitCollection: nil)
            
            let mutableAttar = NSMutableAttributedString(attributedString: textView.attributedText)
            let attach = MQTextAttachment()
            attach.emoticon = emoticon
            let imageHW = textView.font?.lineHeight
            attach.bounds.size = CGSizeMake(imageHW!, imageHW!)
            attach.bounds.origin = CGPointMake(0, -3.5)
            attach.image = image
            
            let attr = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attach))
            attr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, 1))
            
            var range = textView.selectedRange
            mutableAttar.replaceCharactersInRange(range, withAttributedString: attr)
//            mutableAttar.appendAttributedString(attr)
            
            textView.attributedText = mutableAttar
            range.location += 1
            range.length = 0
            textView.selectedRange = range
            
            //调用textview的代理方法，改变sendBtn的enable状态
            textView.delegate?.textViewDidChange?(textView)
            //发送通知，改变placeholderLabel的hidden状态
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
            
        }else if emoticon.type == "1"{
            //emoji表情
            textView.insertText((emoticon.code! as NSString).emoji())
        }
        
    }
    
    @objc private func keyBoardChangeFrame(noti:NSNotification){
//        printfLog(noti)
        if composeToolBarAnimation == false{
            return
        }
        if let endFrame =  (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"] as? NSValue)?.CGRectValue(){
//            printfLog(endFrame)
            //改变textview的约束
            self.composeToolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(self.view).offset(endFrame.origin.y - SCREENH)
            })
            
        }
        
        if let duration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as? NSNumber)?.doubleValue{
            UIView.animateWithDuration(duration, animations: { () -> Void in
                self.composeToolBar.layoutIfNeeded()
            })
        }
    }
    private func setupUI(){
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didClickEmoticonBtn:", name: MQEoticonDidSelectedBtnNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didClickDeleteBtn", name: MQDeleteButtonClickNotification, object: nil)
        
        view.backgroundColor = UIColor.grayColor()
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "back")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendBtn)
        self.navigationItem.rightBarButtonItem?.enabled = false
        navigationItem.titleView = titleLabel
        
        //添加控件
        view.addSubview(textView)
        view.addSubview(composeToolBar)
        textView.addSubview(composePictureView)
   
        
        //添加约束
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view)
        }
        composeToolBar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self.view)
            make.bottom.equalTo(self.view)
            make.trailing.equalTo(self.view)
            make.height.equalTo(44)
        }
        composePictureView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(textView.snp_leading).offset(8)
            make.width.equalTo(textView.snp_width).offset(-16)
            make.top.equalTo(textView.snp_top).offset(100)
            make.height.equalTo(composePictureView.snp_width)
        }
    }
    
    @objc private func back(){
        self.dismissViewControllerAnimated(true , completion: nil)
    }
 
    // MARK: - 懒加载控件
    private lazy var emoticonKeyBoard:MQEmoticonKeyBoard = {
        let emoticonKeyBoard = MQEmoticonKeyBoard()
        emoticonKeyBoard.frame.size = CGSizeMake(SCREENW, 200)
        return emoticonKeyBoard
    }()
    
    private lazy var composePictureView:MQComposePictureView = {
       let picture = MQComposePictureView()
        picture.didClickPauseCell = {[weak self] in
            self?.selectPicture()
        }
        return picture
    
    }()
    
    private lazy var titleLabel:UILabel = {
        let titleLabel = UILabel()
        
        if let name = MQUserAccountViewModel.shareUserAccountViewModel.userAccount?.screen_name{
            let titleString = "发微博\n\(name)"
            let attr = NSMutableAttributedString(string:titleString)
            let range = (titleString as NSString).rangeOfString(name)
            
            let attrs = [
                NSFontAttributeName : UIFont.systemFontOfSize(14),
                NSForegroundColorAttributeName: UIColor.lightGrayColor()
            ]
            attr.addAttributes(attrs, range: range)
//            attr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: range)
            
            titleLabel.attributedText = attr
            
            titleLabel.numberOfLines = 0
            titleLabel.textAlignment = .Center
            
        }else{
            titleLabel.text = "发微博"
        }
       titleLabel.sizeToFit()
        return titleLabel
    }()
    
    
    private lazy var sendBtn:UIButton = {
        let btn = UIButton()
        
        btn.addTarget(self, action: "didClickSendBtn", forControlEvents: UIControlEvents.TouchUpInside)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        
        //字体颜色
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.grayColor(), forState: UIControlState.Disabled)
        //字体内容与大小
        btn.setTitle("发送", forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        //frame
        btn.frame.size = CGSizeMake(40, 30)
        
        
        return btn
    }()
    
    @objc private func didClickSendBtn(){
        
    
        if composePictureView.images.count == 0{
            updata()
        }else{
            upload()
        }
    }
    
    @objc private func didClickDeleteBtn(){
        textView.deleteBackward()
    }
    
    //上传数据
    private func updata(){
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        let params = [
            "access_token":MQUserAccountViewModel.shareUserAccountViewModel.accessToken!,
            "status":textView.textEmoticon()
        ]
        
        
        MQNetWorkTools.sharedTools.request(MQRequestMethod.POST, urlString: urlString, parameters: params) { (response, error) -> () in
            if error != nil{
                SVProgressHUD.showErrorWithStatus("发送失败")
                return
            }
            
            SVProgressHUD.showWithStatus("发送成功")
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()){
                SVProgressHUD.dismiss()
            }
        }

    }
    
    //上传图片
    private func upload(){
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        let params = [
            "access_token":MQUserAccountViewModel.shareUserAccountViewModel.accessToken!,
            "status":textView.textEmoticon()
        ]
        
        let manager = AFHTTPSessionManager()
        
        manager.POST(urlString, parameters: params, constructingBodyWithBlock: { (formdata) -> Void in
                let image = self.composePictureView.images.first!
            
                formdata.appendPartWithFileData(UIImagePNGRepresentation(image)!, name: "pic", fileName: "aabb", mimeType: "application/octet-stream")
            }, progress: { (_) -> Void in
                //不执行任何回调操作
            }, success: { (_, response) -> Void in
                SVProgressHUD.showWithStatus("发送成功")

            }) { (_, NSError) -> Void in
                SVProgressHUD.showErrorWithStatus("发送失败")

        }
        
    }
    
    private lazy var textView:MQTextView = {
        let textView = MQTextView()
        textView.delegate = self
        textView.placeholder = "听说下雨天和辣条更配喔"
        textView.font = UIFont.systemFontOfSize(15)
        textView.alwaysBounceVertical = true
//        textView.keyboardDismissMode = .OnDrag
        return textView
    }()
    
    @available(iOS 9.0, *)
    private lazy var composeToolBar:MQComposeToolBar = {
        let composeToolBar = MQComposeToolBar(frame: CGRectZero)
        composeToolBar.buttonClickClosure = {[weak self](btnTagType) -> ()in
//            printfLog(btnTagType.rawValue)
            switch btnTagType{
            case .Picture :
                printfLog("图片")
                self?.selectPicture()
            case .Mention :
                printfLog("@")
            case .Trend :
                printfLog("#")
            case .Emoticon:
                printfLog("😊")
                self?.selectEmoticon()
            case .Add :
                printfLog("➕")
            }
        }
        return composeToolBar
    }()
    
    private func selectEmoticon(){
        composeToolBarAnimation = false
        textView.resignFirstResponder()
        if textView.inputView == nil{
            textView.inputView = emoticonKeyBoard
            composeToolBar.isSystemKeyBoard = false
        
        }else{
            textView.inputView = nil
            composeToolBar.isSystemKeyBoard = true
        }
        composeToolBarAnimation = true
        //使textView成为第一响应者
        textView.becomeFirstResponder()
    }
    
    @objc private func selectPicture(){
        let vc = UIImagePickerController()
        vc.sourceType = .PhotoLibrary
        vc.delegate = self
        presentViewController(vc, animated: true, completion: nil)
    }
}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate代理
extension MQComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    //选择图片
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        self.textView.backgroundColor = UIColor(patternImage: image)
        
        
        composePictureView.addImage(image.scaleImagWidth(300))
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    //取消选择图片
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
}

// MARK: - UITextViewDelegate代理
extension MQComposeViewController{
    func textViewDidChange(textView: UITextView){
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
//        printfLog("xxxxxx")
    }
//    func scrollViewDidScroll(scrollView: UIScrollView) {
//        textView.endEditing(true)
//    }
}
